package com.basics.common.utils.weixin;

import com.basics.common.constant.Constants;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 调用微信支付统一下单接口，所需参数处理工具类
 *--------------------------------------------------->
 * @Author WangWei
 * @date 2021年5月08日 下午2:32:20
 * @version V1.0
 * @Email 1246518873@qq.com
 *--------------------------------------------------->
 * @Description:
 *
 *
 */
public class WeixinPayCommonUtil {

	/**
	 * 对排序后的Map集合，进行处理（去掉其中的value为空的key）
	 *
	 * @param packageParams：需要进行处理的SortedMap集合
	 * @return
	 */
	public static SortedMap<Object, Object> doOutNullValue(SortedMap<Object, Object> packageParams) {

		SortedMap<Object, Object> resultMap = new TreeMap<Object, Object>();

		Set es = packageParams.entrySet();

		Iterator it = es.iterator();

		while (it.hasNext()) {

			Map.Entry entry = (Map.Entry) it.next();

			String key = (String) entry.getKey();

			String value = (String) entry.getValue();

			if (!"sign".equals(key) && !"key".equals(key) && null != value && !"".equals(value)&& !"null".equals(value)) {

				resultMap.put(key, value);

			}

		}

		return resultMap;

	}

	/**
	 * 判断签名是否正确，规则是：按照参数名称字典排序，遇到空值的参数不参加签名
	 *
	 * @param characterEncoding：编码格式UTF-8
	 * @param packageParams：计算摘要的参数Map集合
	 * @param API_KEY：公众号的API_KEY
	 * @return
	 */
	public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams,
			String API_KEY) {

		StringBuffer sb = new StringBuffer();

		Set es = packageParams.entrySet();

		Iterator it = es.iterator();

		while (it.hasNext()) {

			Map.Entry entry = (Map.Entry) it.next();

			String key = (String) entry.getKey();

			String value = (String) entry.getValue();

			if (!"sign".equals(key) && !"key".equals(key) && null != value && !"".equals(value)) {

				sb.append(key + "=" + value + "&");

			}

		}

		sb.append("key=" + API_KEY);
		// 算出签名
		String mySign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();

		String tenpaySign = ((String) packageParams.get("sign")).toLowerCase();

		return tenpaySign.equals(mySign);

	}


	/**
	 * 使用将要请求的参数列表集合（除开sign和key）算出签名（sign）
	 *
	 * @param characterEncoding
	 * @param packageParams
	 * @param API_KEY
	 * @return
	 */
	public static String createSign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {

		StringBuffer sb = new StringBuffer();

		Set es = packageParams.entrySet();

		Iterator it = es.iterator();

		while (it.hasNext()) {

			Map.Entry entry = (Map.Entry) it.next();

			String key = (String) entry.getKey();

			String value = (String) entry.getValue();

			if (null != value && !"".equals(value) && !"sign".equals(key) && !"key".equals(key)) {

				sb.append(key + "=" + value + "&");

			}

		}

		sb.append("key=" + API_KEY);

		// 算出签名
		String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();

		return sign;

	}

	/**
	 * 将请求参数转为XML格式的String
	 *
	 * @param sortedMap
	 * @return
	 */
	public static String getRequestXml(SortedMap<Object, Object> sortedMap) {

		StringBuffer sb = new StringBuffer();

		sb.append("<xml>");

		Set es = sortedMap.entrySet();

		Iterator it = es.iterator();

		while (it.hasNext()) {

			Map.Entry entry = (Map.Entry) it.next();

			String k = (String) entry.getKey();

			String v = String.valueOf(entry.getValue());

			if (null != v && !"".equals(v)) {
				if ("detail".equalsIgnoreCase(k)) {

					sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");

				} else {

					sb.append("<" + k + ">" + v + "</" + k + ">");

				}
			}

		}

		sb.append("</xml>");

		return sb.toString();

	}

	/**
	 * 取出一个指定长度大小的随机正整数
	 *
	 * @param length
	 * @return
	 */
	public static int buildRandom(int length) {

		int num = 1;

		double random = Math.random();

		if (random < 0.1) {

			random = random + 0.1;

		}

		for (int i = 0; i < length; i++) {

			num = num * 10;

		}

		return (int) ((random * num));

	}

	/**
	 * 获取当前时间 yyyyMMddHHmmss
	 *
	 * @return
	 */
	public static String getCurrTime() {

		Date now = new Date();

		SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");

		String s = outFormat.format(now);

		return s;

	}

	/**
	 * 获得订单号：订单号生成规则 （当前时间的 yyyyMMddHHmmss+13位的系统时间long型+5位随机数）
	 *
	 * @return
	 */
	public static String getOrderNumber() {

		String str_1 = getCurrTime();

		String str_2 = Long.toString(System.currentTimeMillis());

		String str_3 = Integer.toString(buildRandom(5));

		String orderNumber = str_1 + str_2 + str_3;

		return orderNumber;

	}

	public static String QRfromGoogle(String chl) throws Exception {
	    int widhtHeight = 300;
	    String EC_level = "L";
	    int margin = 0;
	    chl = UrlEncode(chl);
	    String QRfromGoogle = "http://chart.apis.google.com/chart?chs=" + widhtHeight + "x" + widhtHeight
	            + "&cht=qr&chld=" + EC_level + "|" + margin + "&chl=" + chl;

	    return QRfromGoogle;
	}

	public static String QRfromBizpayurl(String product_id,String nonce_str,String time_stamp,String sign,String appid,String secret){
		 String QRfromUrl = "weixin://wxpay/bizpayurl?appid="+ appid+"&mch_id="+secret
				 +"&product_id="+product_id+"&time_stamp="+time_stamp+"&nonce_str="+nonce_str+"&sign="+sign;
		 return QRfromUrl;
	}

	// 特殊字符处理
	public static String UrlEncode(String src)  throws UnsupportedEncodingException {
	    return URLEncoder.encode(src, "UTF-8").replace("+", "%20");
	}

}
